/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.full.command;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.SimpleDoc;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.commons.command.Command;
import br.ufmg.dees.insane.commons.view.ExtensionFileFilter;
import br.ufmg.dees.insane.ui.rich.full.InsaneInternalInterface;

/**
 * This class is an implementation of the interface Command.
 * its unabled to undo or redo.
 * its "execute" method encodes the current drawing image as
 * a postscript in a given file.
 *
 * @author Fonseca, Flavio & Pitangueira, Roque
 * @since February 2004
 * @see gui.command.Command
 */
public class ExportPSCommand implements Command {
    
    private InsaneInternalInterface parent;
    private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter("ps", "PostScript Files");
    private boolean validFile;
	
//*****************************************************************************
	
    /**
     * Creates new ExportPSCommand
     * and sets the FileFilter do FileChooser.
     *
     * @param parent The JInternalFrame parent.
     */
    public ExportPSCommand(JInternalFrame parent) {
        this.parent = (InsaneInternalInterface)parent;
        fileChooser.setFileFilter(filter);
    }
    
//*****************************************************************************
	
    /**
     * Calls the file chooser an encode the drawing as an image JPEG.
     *
     * @see gui.command.Command#execute()
     */
    public void execute() {
        
		validFile = false;
		while (!validFile) {
			
			fileChooser.setDialogTitle("Export PostScript");
			int retVal = fileChooser.showDialog(parent, "Export");
			if (retVal == JFileChooser.APPROVE_OPTION) {
				//Getting the file name
				String s = fileChooser.getSelectedFile().getName();
				//Getting the file extension
				String ext = new String();
				int i = s.lastIndexOf('.');
				if (i > 0 &&  i < s.length() - 1) {
					ext = s.substring(i+1).toLowerCase();
				}
				//Comparing the extension
				if (!ext.equals("ps")){
					s = s + ".ps";
					File file = fileChooser.getSelectedFile();
					//Changing the file in case of no good extensions
					fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
				}
				//Checks if the file exists
				if (fileChooser.getSelectedFile().exists()){
					int value = 10;
					value = JOptionPane.showConfirmDialog(parent, 
					"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
					"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
					if (value == JOptionPane.YES_OPTION){
						validFile = true;
					}
				}
				else {
					validFile = true;
				}
			}
			else return;
		}
		
		/* Use the pre-defined flavor for a Printable from an InputStream */
		DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
		
		/* Specify the type of the output stream */
		String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
		
		/* Locate factory which can export a GIF image stream as Postscript */
		StreamPrintServiceFactory[] factories =
		StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
		flavor, psMimeType);
		if (factories.length == 0) {
			System.err.println("No suitable factories");
			return;
		}
		
		try {
			/* Create a file for the exported postscript */
			FileOutputStream fos = new FileOutputStream(fileChooser.getSelectedFile().getPath());
			
			/* Create a Stream printer for Postscript */
			StreamPrintService sps = factories[0].getPrintService(fos);
			
			/* Create and call a Print Job */
			DocPrintJob pj = sps.createPrintJob();
			PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
			aset.add(OrientationRequested.LANDSCAPE);
			
			Doc doc = new SimpleDoc(parent.getDrawing(), flavor, null);
			
			pj.print(doc, aset);
			fos.close();
			parent.addOutputText("File \"" + fileChooser.getSelectedFile().getPath() + "\" successfully exported.");
			
		} catch (PrintException pe) {
			System.err.println(pe);
		} catch (IOException ie) {
			System.err.println(ie);
		}
		
	}
    
//*****************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
//*****************************************************************************
	
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//*****************************************************************************
}

